<template>
  <div id="addinfopage">
    <el-dialog title="预览" :visible.sync="previewVisible" width="1200px" :close-on-click-modal="false" :close-on-press-escape="false">
      <table width="100%" border="0" cellpadding="15" cellspacing="1" class="inputtable">
        <tr>
          <td width="100" align="center" valign="top" bgcolor="#F9FBFB"><strong>信息类别</strong></td>
          <td valign="top" bgcolor="#FFFFFF">
            {{ infoClassName() }}
          </td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>姓名</strong></td>
          <td valign="top" bgcolor="#FFFFFF">{{ postForm.realname }}</td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>身份证号</strong></td>
          <td valign="top" bgcolor="#FFFFFF">{{ postForm.idcard }}</td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>内容</strong></td>
          <td valign="top" bgcolor="#FFFFFF" style="word-wrap:break-word; word-spacing:normal;">
            <div id="pre_content" style="word-wrap:break-word; word-spacing:normal;">
              <div>{{ alltext }}</div>
              <div>字数：{{ textNum }}</div></div>
          </td>
        </tr>
        <tr v-if="paperFlag === '1'">
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>加黑提前</strong></td>
          <td valign="top" bgcolor="#FFFFFF">{{ showTextB() }}</td>
        </tr>
        <tr v-if="paperFlag === '1'">
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>刊登期数</strong></td>
          <td valign="top" bgcolor="#FFFFFF" style="word-wrap:break-word; word-spacing:normal;">
            <div id="pre_vol" style="word-wrap:break-word; word-spacing:normal;">
              {{ postForm.vols }}
            </div>
            <div>
              共 {{ postForm.vols ? postForm.vols.toString().split(',').length : 0 }} 期
              <span v-if="!week1||!week3||!week5">
                ，只登<span v-if="week1">周一</span><span v-if="week3">周三</span><span v-if="week5">周五</span>
              </span>
            </div>
          </td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>微信小程序</strong></td>
          <td valign="top" bgcolor="#FFFFFF" style="word-wrap:break-word; word-spacing:normal;">
            <div v-if="postForm.weixin" style="word-wrap:break-word; word-spacing:normal;">
              同步刊登至微信小程序<span v-if="postForm.wxTopDays" style="margin-left:20px">置顶{{ postForm.wxTopDays }}天</span>
            </div>
            <div>
              刊登 {{ postForm.wxPublishDays }} 天
              <span v-if="checkedWeek.length>0 && checkedWeek.length<7">（{{ translateWeekContent(checkedWeek) }}）</span>
              <span v-if="wxPublishText">：{{ wxPublishText }}</span>
            </div>
            <div>
              置顶 {{ postForm.wxTopDays }} 天
            </div>
          </td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>备注</strong></td>
          <td valign="top" bgcolor="#FFFFFF">{{ postForm.remark }}</td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB"><strong>提示信息</strong></td>
          <td valign="top" bgcolor="#FFFFFF">
            <span id="pre_message" />
            <span v-if="paperFlag === '1'">
              <span v-if="textNum>limitTextNum && postForm.vols>0">&nbsp;超{{ textNum - limitTextNum }}字</span>
              <span>&nbsp;报纸{{ pricePaper }}元</span>
              <span>&nbsp;小程序{{ priceXcx }}元</span>
            </span>
            <span>&nbsp;共{{ allPrice }}元</span>
            <span v-if="postForm.memberCard">（使用会员卡）</span>
            <span v-if="postForm.infoStation">（信息站信息）</span>
          </td>
        </tr>
        <tr>
          <td align="center" valign="top" bgcolor="#F9FBFB" />
          <td valign="top" bgcolor="#FFFFFF">
            <el-button v-if="!submitSuccess" type="success" :loading="loading" @click="addInfo">确定</el-button>
            <el-button v-if="!submitSuccess" :loading="loading" @click="previewVisible=false">取消</el-button>
            <el-button v-if="submitSuccess" type="primary" :loading="loading" @click="printInfo(printInfoId)">打印</el-button>
            <el-button v-if="submitSuccess" type="info" :loading="loading" @click="newInput">返回</el-button>
          </td>
        </tr>
      </table>
    </el-dialog>
    <el-dialog title="期数日历" :visible.sync="calendarVisible" width="1200px" :close-on-click-modal="false" :close-on-press-escape="false">
      <!-- {{ selectVols }} -->
      <el-calendar v-model="myMonth">
        <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
        <template
          slot="dateCell"
          slot-scope="{date, data}"
        >
          <div v-if="showVolName(data.day)" style="height:70px;" @click="addVol(showVolName(data.day))">
            <div style="font-weight:bolder;color:blue;line-height:150%" v-html="data.day+'<br>第'+formatYear(showVolName(data.day))+'期'" />
            <div v-if="selectVols.indexOf(showVolName(data.day))!==-1">✔️</div>
          </div>
          <div v-else>{{ data.day }}</div>
        </template>
      </el-calendar>
    </el-dialog>
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="200px" :inline="true">
      <!-- <el-form-item label="处非案件编号" prop="cfajbh" style="width:500px;">
        {{ postForm.id?postForm.cfajbh:'自动生成' }}
      </el-form-item> -->
      <table cellspacing="0" cellpadding="0" border="0" class="formTable" style="margin-bottom:10px;">
        <tr>
          <th>分类</th>
          <td>
            <el-form-item label="" prop="infoClass" style="width:500px;">
              <template v-if="!readOnly">
                <el-select v-model="postForm.infoClassP" placeholder="请选择" @change="postForm.infoClass=null">
                  <el-option
                    v-for="group in infoClassList"
                    :key="group.id"
                    :label="group.classname"
                    :value="group.id"
                  />
                </el-select>
                <el-select v-if="postForm.infoClassP" v-model="postForm.infoClass" placeholder="请选择" @change="changeInfoClass">
                  <el-option
                    v-for="item in infoClassList.find(item=>item.id===postForm.infoClassP).children"
                    :key="item.id"
                    :label="item.classname"
                    :value="item.id"
                  />
                </el-select>
              </template>
              <!-- <el-select v-if="!readOnly" v-model="postForm.infoClass" placeholder="请选择" @change="changeInfoClass">
                <el-option-group
                  v-for="group in infoClassList"
                  :key="group.id"
                  :label="group.classname"
                >
                  <el-option
                    v-for="item in group.children"
                    :key="item.id"
                    :label="item.classname"
                    :value="item.id"
                  />
                </el-option-group>
              </el-select> -->
              <span v-else>{{ postForm.infoClass }}</span>
            </el-form-item>
          </td>
          <th>姓名</th>
          <td>
            <el-form-item label="" prop="realname">
              <el-input v-if="!readOnly" v-model="postForm.realname" />
              <span v-else>{{ postForm.realname }}</span>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th>身份证号</th>
          <td>
            <el-form-item label="" prop="idcard">
              <el-input v-if="!readOnly" v-model="postForm.idcard" />
              <span v-else>{{ postForm.idcard }}</span>
            </el-form-item>
          </td>
          <th>备注</th>
          <td>
            <el-form-item label="" prop="remark">
              <el-input v-if="!readOnly" v-model="postForm.remark" style="width:350px" />
              <span v-else>{{ postForm.remark }}</span>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th v-html="'内容'" />
          <td colspan="3">
            <div>
              <el-form-item label="" prop="title">
                <el-input v-model="postForm.title" style="width:800px;clear:both" @input="changeTextNum" />
              </el-form-item>
              <el-form-item label="" prop="content" style="margin-top:0px">
                <el-input v-model="postForm.content" style="width:800px;clear:both;margin-top:0px" rows="4" type="textarea" @input="changeTextNum" />
              </el-form-item>
              <div style="margin:0 0 15px 20px;">
                <div v-if="repeatPhone">电话1：<b>{{ repeatPhone }}</b> <el-button type="text" icon="el-icon-edit" title="修改" @click="editPhone(1)" /> <el-button type="text" icon="el-icon-delete" title="删除" @click="removePhone(1)" /> <el-button v-if="repeatPhone2" type="text" icon="el-icon-sort" title="交换" @click="changePhone()" /></div>
                <div v-if="repeatPhone2">电话2：<b>{{ repeatPhone2 }}</b> <el-button type="text" icon="el-icon-edit" title="修改" @click="editPhone(2)" /> <el-button type="text" icon="el-icon-delete" title="删除" @click="removePhone(2)" /></div>
                <div v-if="!repeatPhone2" style="margin-top:0px">
                  <el-button type="primary" @click="addPhone">{{ repeatPhone?'填写电话2':'填写电话' }}</el-button>
                </div>
                <el-dialog :title="addPhoneFormTitle" :visible.sync="addPhoneFormVisible" width="600px" :close-on-click-modal="false" :close-on-press-escape="false">
                  <el-form ref="addPhoneForm" :model="addPhoneForm" :rules="addPhoneFormRules" @submit.native.prevent>
                    <el-form-item label="" prop="phone">
                      <el-input ref="phoneInput" v-model="addPhoneForm.phone" auto-complete="off" style="width:300px;" :maxlength="50" @keyup.enter.native="addPhoneSubmit" />
                    </el-form-item>
                    <el-form-item label="">
                      <el-button type="primary" @click="addPhoneSubmit">确定</el-button>
                    </el-form-item>
                    <div v-show="showPhoneText" style="margin-left:20px">如果只留一个电话号码请直接确定</div>
                  </el-form>
                </el-dialog>
                <!-- <div>{{ alltext }}</div> -->
                <div v-if="paperFlag === '1'">字数：{{ textNum }}</div>
              </div>
            </div>
          </td>
        </tr>
        <tr>
          <th v-if="paperFlag === '1'">报纸期数</th>
          <td v-if="paperFlag === '1'">
            <el-form-item label="" prop="volnum">
              <!-- <el-date-picker
                v-model="postForm.vols"
                type="dates"
                placeholder="选择一个或多个日期"
              /> -->
              从第<el-input-number v-model="postForm.startVol" :min="minVol" style="width:170px;" @change="setVol" />期开始，刊登
              <el-input-number v-model="postForm.volnum" :min="0" :max="350" style="width:130px;" @change="setVol" />期
              <!-- <el-button type="success" @click="setVol">计算</el-button> -->
              <div>
                <el-checkbox v-model="week1" label="周一" @change="setVol" />
                <el-checkbox v-model="week3" label="周三" @change="setVol" />
                <el-checkbox v-model="week5" label="周五" @change="setVol" />
              </div>
              <div>
                <el-input v-model="postForm.vols" type="textarea" style="width:502px;" rows="2" @blur="checkVols()" />
              </div>
              <div>
                <el-button type="success" icon="el-icon-success" @click="checkVols()">验证</el-button>
                <el-button type="primary" icon="el-icon-date" @click="showCalendar">期数日历</el-button>
              </div>
            </el-form-item>
          </td>
          <th>微信小程序</th>
          <td :colspan="paperFlag === '1' ? 0 : 3" style="vertical-align: top">
            <!-- <el-form-item v-if="$route.query.type === 2&&status>1" label="" prop="weixin"> -->
            <el-form-item v-if="$route.query.type === 2" label="" prop="weixin">
              <!-- <div v-if="postForm.weixin">同步刊登至微信小程序</div>
              <div v-if="postForm.weixin&&postForm.wxTopDays">置顶 {{ postForm.wxTopDays }} 天</div> -->
              <div v-if="postForm.wxPublishDays">
                刊登 {{ postForm.wxPublishDays }} 天
                <span v-if="wxWeeksText">（只登{{ wxWeeksText }}）</span>
              </div>
              <div v-if="postForm.wxTopDays">
                置顶 {{ postForm.wxTopDays }} 天
              </div>
            </el-form-item>
            <el-form-item v-else label="" prop="weixin">
              <!-- <el-checkbox v-model="postForm.weixin" style="float:left" label="同步刊登至微信小程序" @change="setAllPrice" /><br> -->
              <div>
                从
                <el-date-picker
                  v-model="postForm.wxDate"
                  type="date"
                  placeholder="请选择日期"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  style="width: 150px;"
                />
                开始，刊登 <el-input-number v-model="postForm.wxPublishDays" :min="0" :max="1000" style="width:130px;" @change="setAllPrice" /> 天
              </div>
              <div>
                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                <el-checkbox-group v-model="checkedWeek" @change="handleCheckedWeeksChange">
                  <el-checkbox v-for="week in weekOptions" :key="week.value" :label="week.value">{{ week.label }}</el-checkbox>
                </el-checkbox-group>
              </div>
              <div style="border-top: 1px solid #DCDFE6; margin-bottom: 14px;" />
              <div>置顶 <el-input-number v-model="postForm.wxTopDays" :min="0" :max="1000" style="width:130px;" @change="setAllPrice" /> 天</div>
            </el-form-item>
          </td>
        </tr>
        <!-- <tr v-if="postForm.pics&&postForm.pics.length>0"> -->
        <tr>
          <th v-html="'图片'" />
          <td colspan="3">
            <el-form-item label="" prop="pics" style="margin-bottom:0">
              <div
                v-for="item in postForm.pics"
                :key="item.id"
                style="float:left"
              >
                <el-image
                  style="width: 100px; height: 100px;margin-right:10px;"
                  :src="$http.defaults.baseURL + 'api/mpfile/download?id=' + item.id"
                  fit="fill"
                  :preview-src-list="postForm.pics.map(item => $http.defaults.baseURL + 'api/mpfile/download?id=' + item.id)"
                />
                <div>
                  <el-popconfirm
                    title="此操作无需保存，立即删除该图片信息，确定删除吗？"
                    @onConfirm="delPic(item.id)"
                  >
                    <el-button slot="reference" type="text" style="text-align:center;margin:0 0 0 33px;">删除</el-button>
                  </el-popconfirm>
                </div>
              </div>
              <el-upload
                style="float:left"
                class="avatar-uploader"
                :action="this.$http.defaults.baseURL+'api/mpfile/upload/'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="myHeaders"
                accept="image/jpeg,image/png,image/gif"
                multiple
              >
                <i class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </td>
        </tr>
        <tr>
          <th v-if="paperFlag === '1'">加黑提前</th>
          <td v-if="paperFlag === '1'">
            <el-form-item label="" prop="isBold">
              <template v-if="postForm.infoClass===70">
                <el-radio-group v-model="postForm.textb" @change="setTextB">
                  <el-radio style="float:left" :label="2" :disabled="topDisabled2">标下</el-radio>
                  <el-radio style="float:left" :label="3" :disabled="topDisabled3">标头</el-radio>
                </el-radio-group>
                <el-popover
                  v-if="checkedTop"
                  placement="bottom"
                  trigger="hover"
                >
                  <template>
                    <h3>
                      招聘英才标下、标头信息数
                    </h3>
                    <el-table :data="volTopList" class="el-table">
                      <el-table-column width="60" prop="vol" label="期数" align="center" />
                      <el-table-column width="120" prop="num2" label="标下数量" align="center">
                        <template slot-scope="scope">
                          <span v-if="scope.row.num2<21">{{ scope.row.num2 }} / 21</span>
                          <b v-else style="color:red">{{ scope.row.num2 }} / 21</b>
                        </template>
                      </el-table-column>
                      <el-table-column width="120" prop="num3" label="标头数量" align="center">
                        <template slot-scope="scope">
                          <span v-if="scope.row.num3<2">{{ scope.row.num3 }} / 2</span>
                          <b v-else style="color:red">{{ scope.row.num3 }} / 2</b>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                  <i slot="reference" class="el-icon-info" style="margin-left:20px;" />
                </el-popover>
              </template>
              <template v-else>
                <el-checkbox v-model="postForm.isBlack" style="float:left" label="加黑" @change="setTextB" />
                <el-checkbox v-model="postForm.isBold" style="float:left" label="提前" :disabled="topDisabled" @change="setTextB" />
                <el-popover
                  v-if="checkedTop"
                  placement="bottom"
                  trigger="hover"
                >
                  <template>
                    <h3>
                      当前栏目置顶信息数
                    </h3>
                    <el-table :data="volTopList" class="el-table">
                      <el-table-column width="60" prop="vol" label="期数" align="center" />
                      <el-table-column width="120" prop="num" label="置顶数量" align="center">
                        <template slot-scope="scope">
                          <span v-if="scope.row.num2+scope.row.num3<30">{{ scope.row.num2+scope.row.num3 }} / 30</span>
                          <b v-else style="color:red">{{ scope.row.num2+scope.row.num3 }} / 30</b>
                        </template>
                      </el-table-column>
                    </el-table>
                  </template>
                  <i slot="reference" class="el-icon-info" style="margin-left:20px;" />
                </el-popover>
              </template>
            </el-form-item>
          </td>
          <th>价格</th>
          <td :colspan="paperFlag === '1' ? 0 : 3">
            <el-form-item label="" prop="price">
              <div>
                <span v-if="paperFlag === '1'">
                  <span v-if="postForm.infoClass" style="margin-right:20px">
                    <b>
                      {{ infoClassName() }}：
                      <span v-if="classPrice===classPrice2">{{ classPrice }}元/期</span>
                      <span v-else>首期{{ classPrice }}元，第二期起每期{{ classPrice2 }}元</span>
                    </b></span>
                  <span v-if="postForm.textb" style="margin-right:20px"><b>{{ showTextB() }} {{ textbPrice }}元</b></span>
                  <span v-if="textNum>limitTextNum" style="margin-right:20px"><b>字数：{{ textNum }}（超{{ textNum-limitTextNum }}字）{{ Math.ceil((textNum-limitTextNum)/13)*5 }}元</b></span>
                  <b style="margin-right:10px">共{{ postForm.vols ? postForm.vols.toString().split(',').length : 0 }}期</b>
                </span>
                <!-- <b v-if="postForm.weixin" style="margin-left:20px">微信5元<span v-if="postForm.wxTopDays" style="margin-left:10px">置顶{{ postForm.wxTopDays }}天{{ postForm.wxTopDays*10 }}元</span></b> -->
                <b v-if="postForm.wxPublishDays > 0" style="margin-right:10px">微信刊登{{ postForm.wxPublishDays }}天{{ wxPublishPrice }}元</b>
                <b v-if="postForm.wxTopDays > 0">微信置顶{{ postForm.wxTopDays }}天{{ wxTopPrice }}元</b>
              </div>
              <div>
                <el-checkbox v-model="postForm.memberCard" label="会员卡" @change="setInfoType('memberCard')" />
                <el-checkbox v-model="postForm.infoStation" label="信息站" @change="setInfoType('infoStation')" />
                <template v-if="paperFlag === '1'">
                  <span style="margin-left:20px">
                    报纸
                    <template v-if="usertype !== 2">{{ pricePaper }}</template>
                    <template v-else><el-input-number v-model="pricePaper" :min="0" style="width:130px;" @change="handlePriceChange()" /></template>
                    元
                  </span>
                  <span style="margin-left:20px">
                    小程序
                    <template v-if="usertype !== 2">{{ priceXcx }}</template>
                    <template v-else><el-input-number v-model="priceXcx" :min="0" style="width:130px;" @change="handlePriceChange()" /></template>
                    元
                  </span>
                </template>
                <span style="margin-left:20px">
                  合计：
                  <!-- 超字部分多期 -->
                  <!-- <span v-if="textNum>limitTextNum">({{ Math.ceil((textNum-limitTextNum)/13)*5 }})*{{ postForm.vols.toString().split(',').length }}+</span>
                  <span v-if="postForm.textb">
                    ({{ textbPrice }}*{{ postForm.vols.toString().split(',').length }})
                  </span>
                  <span v-else>
                    <span v-if="postForm.vols.toString().split(',').length===1">{{ classPrice }}</span>
                    <span v-else>{{ classPrice }}+{{ classPrice }}*{{ postForm.vols.toString().split(',').length-1 }}</span>
                  </span>
                  = -->
                  <b v-if="$route.query.type === 2">修改前已收金额：{{ oldPrice }}元，修改后金额：</b>
                  <b style="font-size:20px;color:red">
                    <template v-if="usertype===2 && paperFlag!=='1'"><el-input-number v-model="priceXcx" :min="0" style="width:130px;" @change="handlePriceChange()" />&nbsp;元</template>
                    <template v-else>{{ allPrice }}元</template>
                  </b>
                  <!-- <b v-if="usertype!==2" style="font-size:20px;color:red">{{ allPrice }}元</b>
                  <span v-else>{{ allPrice }}元</span> -->
                  <b v-if="$route.query.type === 2">，本次应收：{{ allPrice-oldPrice }}元</b>
                </span>
              </div>
            </el-form-item>
          </td>
          <!-- <th>订单号</th>
          <td>
            <el-form-item label="" prop="orderId">
              <span>{{ postForm.orderId }}</span>
            </el-form-item>
          </td> -->
        </tr>
        <!-- <tr>
          <th>审核情况</th>
          <td colspan="3">
            <el-timeline style="margin-top:10px">
              <el-timeline-item timestamp="2022/4/12 12:10:10" placement="top">录入提交
              </el-timeline-item>
              <el-timeline-item timestamp="2022/4/12 12:10:10" placement="top">审核员（1001）拒绝：xxxx
              </el-timeline-item>
            </el-timeline>
          </td>
        </tr>
        <tr>
          <th>拒绝原因</th>
          <td colspan="3">
            <el-form-item label="" prop="remark">
              <el-input v-if="!readOnly" v-model="postForm.remark" style="width:800px;" />
              <span v-else>{{ postForm.remark }}</span>
            </el-form-item>
          </td>
        </tr> -->
      </table>
      <el-form-item style="margin:0">
        <el-button type="success" :loading="loading" @click="preview(1)">预览</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import qs from 'qs'
const defaultForm = {
  memberCard: false,
  infoStation: false,
  weixin: false,
  wxTopDays: 0,
  duration: 0,
  startDate: [],
  infoClass: '',
  infoClassP: '',
  realname: '',
  phone: '',
  idcard: '',
  volnum: 0,
  isBold: '',
  isBlack: '',
  textb: '',
  content: '',
  title: '',
  pics: [],
  // pics: [
  //   { src: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', url: ['https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg'] },
  //   { src: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', url: ['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'] },
  //   { src: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', url: ['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'] }
  // ],
  price: '',
  // orderId: '',
  // dataCreateDatetime: '',
  // passedList: [],
  remark: '',
  vols: '',
  id: null,
  wxPublishDays: 0,
  wxDate: ''
}
export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    showDuban: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      status: 0,
      oldTextb: 0,
      oldPrice: 0,
      checkedTop: false,
      volTopList: [],
      topDisabled: true,
      topDisabled2: true,
      topDisabled3: true,
      usertype: 0,
      minVol: 0,
      printInfoId: null,
      loading: false,
      submitSuccess: false,
      pickerOptions: { disabledDate(time) { return time.getTime() < Date.now() - 8.64e7 } },
      limitTextNum: 65,
      allPrice: 0,
      textbPrice: 0,
      classPrice: 0,
      classPrice2: 0,
      previewVisible: false,
      selectVols: [],
      monthVolList: [],
      myMonth: null,
      calendarVisible: false,
      infoClassList: [],
      week1: true,
      week3: true,
      week5: true,
      alltext: '',
      phoneStep: 0,
      showPhoneText: false,
      phone: '',
      repeatPhone: '',
      phone2: '',
      repeatPhone2: '',
      addPhoneForm: {
        phone: '',
        phone2: '',
        phoneRemarks: ''
      },
      addPhoneFormRules: {},
      addPhoneFormVisible: false,
      addPhoneFormTitle: '请填写电话号码',
      textNum: 0,
      myHeaders: {},
      postForm: Object.assign({}, defaultForm),
      rules: {
        infoClass: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        realname: [{ validator: validateRequire }],
        vols: [{ validator: validateRequire }]
      },
      paperFlag: null,
      checkAll: true,
      weekOptions: [
        { label: '周一', value: 1 },
        { label: '周二', value: 2 },
        { label: '周三', value: 3 },
        { label: '周四', value: 4 },
        { label: '周五', value: 5 },
        { label: '周六', value: 6 },
        { label: '周日', value: 7 }
      ],
      isIndeterminate: true,
      checkedWeek: [1, 2, 3, 4, 5, 6, 7],
      wxPublishText: '',
      wxPublishPrice: 0,
      wxTopPrice: 0,
      pricePaper: 0,
      priceXcx: 0,
      wxWeeksText: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs['postForm']) {
          this.$refs['postForm'].resetFields()
          this.postForm.pics = []
        }
      },
      immediate: true
    },
    myMonth: {
      handler(val) {
        this.getVolsByDate()
      },
      immediate: true
    }
  },
  mounted() {
    this.usertype = JSON.parse(localStorage.getItem('user')).usertype
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    this.roleName = JSON.parse(localStorage.getItem('user')).roleName
    this.getInfoClass()
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
    this.paperFlag = localStorage.getItem('paperFlag')
    this.handleCheckedWeeksChange(this.checkedWeek)
    this.postForm.wxDate = `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
    window.addEventListener('keydown', this.handkeyCode, true)// 开启监听键盘按下事件
  },
  methods: {
    // 监听报纸、小程序价格变化
    handlePriceChange() {
      this.allPrice = this.pricePaper + this.priceXcx
    },
    // 根据天数和周几返回日期
    getDateWeekStr() {
      this.wxPublishText = ''
      const para = {
        dayNum: this.postForm.wxPublishDays,
        weekList: this.checkedWeek,
        wxDate: this.postForm.wxDate
      }
      if (para.dayNum > 0) {
        if (para.weekList.length === 0) {
          this.$message({
            message: '微信周几显示至少选择一天',
            type: 'error'
          })
          return
        }
        this.loading = true
        this.$http
          .post('/api/busInfo/getDateWeekStr', para)
          .then(response => {
            this.loading = false
            if (response.data.success === true) {
              this.wxPublishText = response.data.result
              this.previewVisible = true
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.loading = false
          })
      } else {
        this.previewVisible = true
      }
    },
    // 翻译周几
    translateWeekContent(weekArr) {
      const result = []
      weekArr.forEach(item => {
        result.push(this.weekOptions.filter(week => week.value === item)[0].label)
      })
      if (result.length > 0) {
        return '只登' + result.join('、')
      } else {
        return ''
      }
    },
    // 周几全选
    handleCheckAllChange(val) {
      this.checkedWeek = val ? this.weekOptions.map(item => item.value) : []
      this.isIndeterminate = false
    },
    handleCheckedWeeksChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.weekOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.weekOptions.length
    },
    handkeyCode(e) {
      let key = null
      if (window.event === undefined) {
        key = e.keyCode
      } else {
        key = window.event.keyCode
      }
      if (key === 13) {
        if (!this.addPhoneFormVisible) {
          if (this.previewVisible) {
            if (this.submitSuccess) {
              this.printInfo(this.printInfoId)
            } else {
              this.addInfo()
            }
          } else {
            this.preview(1) // 登录事件
          }
        }
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess(res, file) {
    // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.postForm.pics.push(res.result[0])
      // this.fileList = []
      // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    delPic(id) {
      this.$http
        .get('/api/genFileInfo/remove?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            // this.getDetail(this.$route.query.id)
            this.postForm.pics = this.postForm.pics.filter(item => item.id !== id)
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getDetail(id) {
      this.loading = true
      this.$http
        .get('/api/busInfo/getById?id=' + id)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            const data = response.data.result
            // 根据type判断，引用还是修改、校对
            this.status = data.status
            this.postForm.infoClass = data.classId
            this.postForm.infoClassP = this.infoClassList.find(item => {
              return item.children.map(it => it.id).includes(data.classId)
            }).id
            this.postForm.realname = data.realname
            this.postForm.phone = data.phone
            this.phone = data.phone
            this.phone2 = data.phone2
            this.repeatPhone = data.phone
            this.repeatPhone2 = data.phone2
            this.postForm.idcard = data.idcard
            this.postForm.content = data.content
            this.postForm.title = data.title
            this.postForm.remark = data.remark
            let alltext = this.postForm.title + ':' + this.postForm.content
            if (this.postForm.phone) {
              alltext = alltext + '。电话：' + this.postForm.phone
            }
            if (this.postForm.phone2) {
              alltext = alltext + ' ' + this.postForm.phone2
            }
            this.alltext = alltext
            this.textNum = data.textnum
            this.postForm.pics = data.files
            if (this.$route.query.type === 2) { // type等于2为改单，否则为引用
              this.oldPrice = data.price
              this.oldTextb = data.textb
              this.postForm.id = data.id
              this.changeTextNum()
              this.postForm.volnum = data.volnum
              if (data.startDate) {
                this.postForm.duration = data.daynum
                this.postForm.startDate = [data.startDate, data.finishDate]
              }
              this.postForm.memberCard = !!data.memberCard
              this.postForm.infoStation = !!data.infoStation
              this.postForm.weixin = !!data.weixin
              this.postForm.wxTopDays = data.wxTopDays
              this.postForm.wxPublishDays = data.wxNum
              const wxWeeksArr = []
              if (data.wxWeek1) {
                wxWeeksArr.push('周一')
              }
              if (data.wxWeek2) {
                wxWeeksArr.push('周二')
              }
              if (data.wxWeek3) {
                wxWeeksArr.push('周三')
              }
              if (data.wxWeek4) {
                wxWeeksArr.push('周四')
              }
              if (data.wxWeek5) {
                wxWeeksArr.push('周五')
              }
              if (data.wxWeek6) {
                wxWeeksArr.push('周六')
              }
              if (data.wxWeek7) {
                wxWeeksArr.push('周日')
              }
              this.wxWeeksText = wxWeeksArr.length !== 7 ? wxWeeksArr.join('、') : ''
              if (this.postForm.infoClass !== 70) {
                this.postForm.isBold = (data.textb === 2 || data.textb === 3)
                this.postForm.isBlack = (data.textb === 1 || data.textb === 3)
              }
              this.postForm.textb = data.textb
              this.postForm.price = data.price
              this.allPrice = data.price
              this.postForm.vols = data.volList.map(item => {
                const year = new Date(item.pubdate).getFullYear()
                const nowYear = new Date().getFullYear()
                if (year !== nowYear) {
                  return (year - 2000) * 1000 + parseInt(item.name)
                } else {
                  return item.name
                }
              }).join(',')
              this.week1 = !!data.week1
              this.week3 = !!data.week3
              this.week5 = !!data.week5
            // 检查所有修改字段，计算改单补交费用，修改改单提交接口，期数验证接口
            // textbPrice: 0,
            // classPrice: 0,
            // classPrice2: 0,
            // selectVols: []
            // this.changeInfoClass()
            }
            this.changeInfoClass()
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.loading = false
          console.log(error)
        })
    },
    printInfo(id) {
    // window.open(this.$http.defaults.baseURL + '/api/busInfo/getPrintHtml?id=' + id)
      window.open('/api/busInfo/getPrintHtml?id=' + id)
    },
    newInput() {
      this.previewVisible = false
      this.submitSuccess = false
      this.allPrice = 0
      this.textbPrice = 0
      this.classPrice = 0
      this.classPrice2 = 0
      this.selectVols = []
      this.week1 = true
      this.week3 = true
      this.week5 = true
      this.alltext = ''
      this.phone = ''
      this.repeatPhone = ''
      this.phone2 = ''
      this.repeatPhone2 = ''
      this.postForm = Object.assign({}, defaultForm)
      this.postForm.pics = []
      this.getDefaultVol()
      this.printInfoId = null
      this.oldPrice = 0
      this.textNum = 0
      this.pricePaper = 0
      this.priceXcx = 0
      this.checkedWeek = [1, 2, 3, 4, 5, 6, 7]
      this.$router.push({ name: 'addinfo', query: { id: null, type: null }})
    },
    add0(num) {
      return num < 10 ? '0' + num : num
    },
    addInfo() {
      const day = new Date()
      const nowDate = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate()) + ' ' + this.add0(day.getHours()) + ':' + this.add0(day.getMinutes()) + ':' + this.add0(day.getSeconds())
      const para = {
        'adddate': nowDate,
        'classId': this.postForm.infoClass,
        'content': this.postForm.content,
        'daynum': this.postForm.duration,
        'finishDate': this.postForm.startDate && this.postForm.startDate.length > 0 ? this.postForm.startDate[1] : null,
        'idcard': this.postForm.idcard,
        'phone': this.repeatPhone,
        'phone2': this.repeatPhone2,
        'price': this.allPrice,
        // 're': 0,
        'realname': this.postForm.realname,
        'remark': this.postForm.remark,
        'startDate': this.postForm.startDate && this.postForm.startDate.length > 0 ? this.postForm.startDate[0] : null,
        'textb': this.postForm.textb,
        'textnum': this.textNum,
        'title': this.postForm.title,
        'volList': this.postForm.vols ? this.postForm.vols.split(',') : [],
        'volnum': this.postForm.vols ? this.postForm.vols.split(',').length : 0,
        'week1': this.week1 ? 1 : 0,
        'week3': this.week3 ? 1 : 0,
        'week5': this.week5 ? 1 : 0,
        memberCard: this.postForm.memberCard ? 1 : 0,
        infoStation: this.postForm.infoStation ? 1 : 0,
        weixin: this.postForm.wxPublishDays > 0 || this.postForm.wxTopDays > 0 ? 1 : 0,
        wxTopDays: this.postForm.wxTopDays,
        fileIds: this.postForm.pics && this.postForm.pics.length > 0 ? this.postForm.pics.map(item => item.id) : null,
        pricePaper: this.pricePaper,
        priceXcx: this.priceXcx,
        wxNum: this.postForm.wxPublishDays,
        wxWeek1: this.checkedWeek.includes(1) ? 1 : 0,
        wxWeek2: this.checkedWeek.includes(2) ? 1 : 0,
        wxWeek3: this.checkedWeek.includes(3) ? 1 : 0,
        wxWeek4: this.checkedWeek.includes(4) ? 1 : 0,
        wxWeek5: this.checkedWeek.includes(5) ? 1 : 0,
        wxWeek6: this.checkedWeek.includes(6) ? 1 : 0,
        wxWeek7: this.checkedWeek.includes(7) ? 1 : 0,
        wxDate: this.postForm.wxDate
      }
      this.loading = true
      let url = '/api/busInfo/save'
      if (this.$route.query.type === 2) {
        para.infoId = this.postForm.id
        para.idCard = para.idcard
        para.remarks = para.remark
        url = '/api/busModInfo/save'
      }
      this.$http.post(url, para)
        .then(response => {
          this.loading = false
          if (response.data.success) {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.printInfoId = response.data.result ? response.data.result : this.$route.query.id
            this.submitSuccess = true
          } else {
            this.$message({
              message: '提交失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.loading = false
          console.log(error)
        })
    },
    setInfoType(str) {
      if (str === 'memberCard' && this.postForm.memberCard) {
        this.postForm.infoStation = false
      }
      if (str === 'infoStation' && this.postForm.infoStation) {
        this.postForm.memberCard = false
      }
      this.setAllPrice()
    },
    setAllPrice() {
      const volnum = this.postForm.vols ? this.postForm.vols.toString().split(',').length : 0
      let overtextPrice = 0
      let textbPrice = 0
      this.pricePaper = 0
      this.priceXcx = 0
      this.allPrice = 0
      if (volnum > 0) {
        if (this.textNum > this.limitTextNum) {
          overtextPrice = Math.ceil((this.textNum - this.limitTextNum) / 13) * 5 * volnum
        }
        if (this.postForm.textb) {
          textbPrice = this.textbPrice * volnum
        } else {
          if (volnum > 1) {
            textbPrice = this.classPrice + this.classPrice2 * (volnum - 1)
          } else {
            textbPrice = this.classPrice
          }
        }
        this.allPrice = overtextPrice + textbPrice
        if (this.postForm.memberCard) {
          this.allPrice = this.allPrice * 0.8
        }
        if (this.postForm.infoStation) {
          this.allPrice = this.allPrice * 0.6
        }
      }
      this.pricePaper = this.allPrice
      if (this.postForm.wxPublishDays > 0 || this.postForm.wxTopDays > 0) {
        this.wxPublishPrice = this.postForm.wxPublishDays * parseInt(localStorage.getItem('priceXcx'))
        this.wxTopPrice = this.postForm.wxTopDays * parseInt(localStorage.getItem('priceXcxTop'))
        this.priceXcx = this.wxPublishPrice + this.wxTopPrice
        if (this.postForm.memberCard) {
          this.priceXcx = this.priceXcx * 0.8
        }
        if (this.postForm.infoStation) {
          this.priceXcx = this.priceXcx * 0.6
        }
        this.allPrice = this.allPrice + this.priceXcx
      }
    },
    infoClassName() {
      let classname = ''
      this.infoClassList.forEach(item => {
        item.children.forEach(it => {
          if (it.id === this.postForm.infoClass) {
            classname = item.classname + ' > ' + it.classname
          }
        })
      })
      return classname
    },
    showTextB() {
      if (this.postForm.infoClass === 70) {
        switch (this.postForm.textb) {
          case 2:
            return '标下'
          case 3:
            return '标头'
        }
      } else {
        switch (this.postForm.textb) {
          case 0:
            return '普通'
          case 1:
            return '加黑'
          case 2:
            return '提前'
          case 3:
            return '加黑+提前'
        }
      }
    },
    setTextB() {
      console.log('错误')
      if (this.postForm.infoClass !== 70) {
        if (this.postForm.isBlack) {
          if (this.postForm.isBold) {
            this.postForm.textb = 3
          } else {
            this.postForm.textb = 1
          }
        } else {
          if (this.postForm.isBold) {
            this.postForm.textb = 2
          } else {
            this.postForm.textb = 0
          }
        }
      }
      if (this.postForm.infoClass === 70) {
        switch (this.postForm.textb) {
          case 2:
            this.textbPrice = 80
            break
          case 3:
            this.textbPrice = 100
            break
        }
      } else {
        switch (this.postForm.textb) {
          case 0:
            this.textbPrice = 0
            break
          case 1:
            this.textbPrice = 25
            break
          case 2:
            this.textbPrice = 30
            break
          case 3:
            this.textbPrice = 55
            break
        }
      }
      // this.checkTopNum()
      this.setAllPrice()
    },
    preview() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          // this.postForm.volnum === 0 && this.postForm.wxPublishDays === 0
          if (this.postForm.volnum === 0 && this.postForm.wxPublishDays === 0 && this.postForm.wxTopDays === 0) {
            this.$message({
              message: '报纸刊登期数和微信小程序刊登天数不能都为0',
              type: 'error'
            })
            return false
          }
          if (!this.repeatPhone) {
            this.$message({
              message: '请填写电话',
              type: 'error'
            })
            return false
          }
          if (this.postForm.infoClass === 70 && this.postForm.textb === 0) {
            this.$message({
              message: '所选期数招聘英才标头标下已满，请选择其他期数',
              type: 'error'
            })
            return false
          }
          if (this.postForm.vols) {
            this.checkVols(null, true)
          } else {
            // this.setAllPrice()
            this.getDateWeekStr()
          }
        }
      })
    },
    changeInfoClass() {
      if (!this.postForm.id) {
        if (this.postForm.infoClass === 70) {
          this.postForm.textb = 2
        } else {
          this.postForm.textb = 0
        }
      }
      this.setTextB()
      this.infoClassList.forEach(item => {
        item.children.forEach(it => {
          if (it.id === this.postForm.infoClass) {
            this.classPrice = it.price
            this.classPrice2 = it.price2
          }
        })
      })
      this.setAllPrice()
      this.checkTopNum()
    },
    checkTopNum() {
      if (!this.postForm.vols) {
        return false
      }
      if (!this.postForm.infoClass) {
        this.$message({
          message: '请先选择栏目',
          type: 'error'
        })
        return false
      }
      const volList = this.postForm.vols.toString().split(',')
      const para = {
        classId: this.postForm.infoClass,
        infoId: this.postForm.id,
        vols: volList
      }
      this.$http.post('/api/busInfo/getTopInfoListByVols', para)
        .then(response => {
          if (response.data.success === true) {
            this.checkedTop = true
            this.volTopList = response.data.result

            if (this.postForm.infoClass === 70) {
              if (this.volTopList.filter(item => item.num2 >= 21).length > 0) {
                this.topDisabled2 = true
              } else {
                this.topDisabled2 = false
              }
              if (this.volTopList.filter(item => item.num3 >= 2).length > 0) {
                this.topDisabled3 = true
              } else {
                this.topDisabled3 = false
              }
              // 根据标头标下是否已满赋值
              // const oldTextb = this.postForm.textb
              if (this.topDisabled2) {
                if (this.topDisabled3) {
                  this.postForm.textb = 0
                } else {
                  this.postForm.textb = 3
                }
              } else {
                if (this.postForm.textb === 3) {
                  if (this.topDisabled3) {
                    this.postForm.textb = 0
                  } else {
                    this.postForm.textb = 3
                  }
                } else {
                  this.postForm.textb = 2
                }
              }
            } else {
              if (this.volTopList.filter(item => item.num2 + item.num3 >= 30).length > 0) {
                this.topDisabled = true
                if (this.postForm.textb === 2 && (this.oldTextb !== 2 && this.oldTextb !== 3)) {
                  this.postForm.textb = 0
                  this.postForm.isBold = false
                } else if (this.postForm.textb === 3 && (this.oldTextb !== 2 && this.oldTextb !== 3)) {
                  this.postForm.textb = 1
                  this.postForm.isBold = false
                }
              } else {
                this.topDisabled = false
              }
            }
          } else {
            this.$message({
              message: '测试失败',
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    formatYear(str) {
      const year = parseInt('20' + str.toString().substring(0, 2))
      const nowYear = new Date().getFullYear()
      if (year === nowYear) {
        return parseInt(str.toString().substring(2, 5))
      } else {
        return str
      }
    },
    addVol(vol) {
      const index = this.selectVols.indexOf(vol)
      if (index === -1) {
        this.selectVols.push(vol)
        this.selectVols = this.selectVols.sort(function(a, b) {
          return parseInt(a) - parseInt(b)
        })
      } else {
        this.selectVols.splice(index, 1)
      }
      this.postForm.vols = this.selectVols.map(item => {
        return this.formatYear(item)
      }).join(',')
    },
    showVolName(date) {
      const item = this.monthVolList.find(item => item.pubdate === date)
      if (item) {
        const year = new Date(item.pubdate).getFullYear()
        let volname = parseInt(item.name)
        volname = (year - 2000) * 1000 + volname
        return volname
      }
    },
    getVolsByDate() {
      const myDate = this.myMonth || new Date()
      const month = myDate.getMonth() + 1
      const year = myDate.getFullYear()
      this.$http
        .get('/api/busVol/getVolByDate?year=' + year + '&month=' + month)
        .then(response => {
          if (response.data.success === true) {
            this.monthVolList = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    showCalendar() {
      this.checkVols()
      this.calendarVisible = true
      this.getVolsByDate()
    },
    getDefaultVol(flag) {
      this.$http
        .get('/api/busVol/getDefaultVol')
        .then(response => {
          if (response.data.success === true) {
            let defaultVol = response.data.result.name
            const pubdate = new Date(response.data.result.pubdate)
            const nowYear = new Date(response.data.result.pubdate).getFullYear()
            if (pubdate.getFullYear() !== nowYear) {
              defaultVol = (pubdate.getFullYear() - 2000) * 1000 + parseInt(defaultVol)
            }
            this.postForm.startVol = defaultVol
            this.minVol = defaultVol
            // this.postForm.vols = defaultVol
            if (flag) {
              if (this.$route.query.id) {
                this.getDetail(this.$route.query.id)
              }
            }
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getInfoClass() {
      this.$http
        .get('/api/busInfoClass/getLevelList')
        .then(response => {
          if (response.data.success === true) {
            this.infoClassList = response.data.result
            this.getDefaultVol(true)
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    GetNumberOfDays(date1, date2) { // 获得天数
    // date1：开始日期，date2结束日期
      var a1 = Date.parse(new Date(date1))
      var a2 = Date.parse(new Date(date2))
      var day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24))// 核心：时间戳相减，然后除以天数
      return day
    },
    setDuration() {
      this.postForm.duration = this.GetNumberOfDays(this.postForm.startDate[0], this.postForm.startDate[1]) + 1
      this.setAllPrice()
    },
    changePhone() {
      const repeatPhone = this.repeatPhone
      this.repeatPhone = this.repeatPhone2
      this.repeatPhone2 = repeatPhone
      const phone = this.phone
      this.phone = this.phone2
      this.phone2 = phone
    },
    addPhoneSubmit() {
      if (this.addPhoneForm.phone) {
        if (this.phoneStep === 0) {
          this.phone = this.addPhoneForm.phone
          this.phoneStep = 1
          this.showPhoneForm()
        } else {
          if (this.phoneStep === 1) {
            if (this.addPhoneForm.phone === this.phone) {
              this.repeatPhone = this.addPhoneForm.phone
              if (this.repeatPhone2) {
                this.addPhoneFormVisible = false
              } else {
                this.phoneStep = 2
                this.showPhoneForm()
              }
            } else {
              this.$message({
                message: '两次输入电话号码不一致',
                type: 'error'
              })
              this.addPhoneForm.phone = ''
            }
          } else {
            if (this.phoneStep === 2) {
              this.phone2 = this.addPhoneForm.phone
              this.phoneStep = 3
              this.showPhoneForm()
            } else {
              if (this.phoneStep === 3) {
                if (this.addPhoneForm.phone === this.phone2) {
                  this.repeatPhone2 = this.addPhoneForm.phone
                  this.addPhoneFormVisible = false
                } else {
                  this.$message({
                    message: '两次输入电话号码不一致',
                    type: 'error'
                  })
                  this.addPhoneForm.phone = ''
                }
              }
            }
          }
        }
      } else {
        if (this.phoneStep === 2) {
          this.addPhoneFormVisible = false
        } else {
          this.$message({
            message: '电话号码不能为空',
            type: 'error'
          })
        }
      }
      this.changeTextNum()
    },
    showPhoneForm(phone) {
      this.addPhoneForm.phone = phone || ''
      this.addPhoneFormVisible = true
      this.showPhoneText = false
      switch (this.phoneStep) {
        case 0:
          this.addPhoneFormTitle = '请填写电话号码'
          break
        case 1:
          this.addPhoneFormTitle = '请再次输入电话号码'
          break
        case 2:
          this.addPhoneFormTitle = '请填写电话号码2'
          this.showPhoneText = true
          break
        case 3:
          this.addPhoneFormTitle = '请再次输入电话号码2'
          break
      }
      this.$nextTick(() => {
        this.$refs['phoneInput'].focus()
      })
    },
    addPhone() {
      if (!this.repeatPhone) {
        this.phone = ''
        this.phoneStep = 0
        this.showPhoneForm()
      } else {
        if (!this.repeatPhone2) {
          this.phone2 = ''
          this.phoneStep = 2
          this.showPhoneForm()
        }
      }
    },
    removePhone(num) {
      if (num === 1) {
        this.phone = this.phone2
        this.repeatPhone = this.repeatPhone2
      }
      this.phone2 = ''
      this.repeatPhone2 = ''
    },
    editPhone(num) {
      if (num === 1) {
        this.phoneStep = 0
        this.showPhoneForm(this.phone)
      } else if (num === 2) {
        this.phoneStep = 2
        this.showPhoneForm(this.phone2)
      }
    },
    changeTextNum() {
      let alltext = this.postForm.title + ':' + this.postForm.content
      if (this.repeatPhone) {
        alltext = alltext + '。电话：' + this.repeatPhone
      }
      if (this.repeatPhone2) {
        alltext = alltext + ' ' + this.repeatPhone2
      }
      this.alltext = alltext
      this.textNum = Math.ceil(this.realLength(alltext) / 2)
      this.setAllPrice()
    },
    realLength(str) {
      let curlen = 0
      for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) {
          curlen += 2
        } else {
          curlen++
        }
      }
      return curlen
    },
    setVol() {
      this.postForm.vols = ''
      this.$http
      // .get('/api/busVol/getVolList?startVol='+this.postForm.startVol+'&num='+this.postForm.volnum+,)
        .get('/api/busVol/getVolList?' + qs.stringify({ startVol: this.postForm.startVol, num: this.postForm.volnum, week1: this.week1, week3: this.week3, week5: this.week5 }))
        .then(response => {
          if (response.data.success === true) {
            const vols = response.data.result.map(item => {
              const year = new Date(item.pubdate).getFullYear()
              const nowYear = new Date().getFullYear()
              if (year !== nowYear) {
                return (year - 2000) * 1000 + parseInt(item.name)
              } else {
                return item.name
              }
            })
            this.checkVols(vols)
          } else {
            this.postForm.vols = ''
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    checkVols(vols, flag) {
      let checkVolList = vols || this.postForm.vols.toString().replace(/，/g, ',').replace(/。/g, ',').replace(/\./g, ',').split(',')
      checkVolList = [...new Set(checkVolList)]
      // 此处有过去年份排序错误的问题，比如21001会排到100期后面
      checkVolList = checkVolList.sort(function(a, b) {
        return parseInt(a) - parseInt(b)
      })
      checkVolList = checkVolList.filter(item => item)
      const weekList = []
      if (this.week1) { weekList.push(1) }
      if (this.week3) { weekList.push(3) }
      if (this.week5) { weekList.push(5) }
      if (checkVolList && checkVolList.length > 0) {
        this.$http.post('/api/busVol/checkVolList', { volList: checkVolList, beforeDefault: this.$route.query.type === 2, weekList: weekList })
          .then(response => {
            if (response.data.result === true) {
              this.postForm.vols = checkVolList.join(',')
              this.selectVols = this.postForm.vols.split(',').map(item => {
                if (parseInt(item) < 1000) {
                  return (new Date().getFullYear() - 2000) * 1000 + parseInt(item)
                } else {
                  return parseInt(item)
                }
              })
              if (flag) {
                if (this.postForm.wxPublishDays > 0 || this.postForm.wxTopDays > 0) {
                  this.getDateWeekStr()
                } else {
                  this.previewVisible = true
                }
              } else {
                this.setAllPrice()
              }
              this.checkTopNum()
              // const pubdate = new Date(response.data.result.pubdate)
              // const nowYear = new Date(response.data.result.pubdate).getFullYear()
              // if (pubdate.getFullYear() !== nowYear) {
              //   this.postForm.startVol = (pubdate.getFullYear() - 2000) * 1000 + parseInt(this.postForm.startVol)
              // }
              // console.log('this.postForm.startVol')
              // console.log(this.postForm.startVol)
            } else {
              this.postForm.vols = ''
              this.$message({
                message: '期数填写有误',
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
          })
      } else {
        this.setAllPrice()
      }
    }
  }
}
</script>

<style>
  #addinfopage .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  #addinfopage .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  #addinfopage .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .is-selected {
    color: #1989FA;
  }
.formTable{
  border-top:1px solid #dfe6ec;
  border-left:1px solid #dfe6ec;
  width: 100%;
}
.formTable td{
  border-bottom:1px solid #dfe6ec;
  border-right:1px solid #dfe6ec;
  margin:0;
  min-width: 500px;
  vertical-align: middle;
}
.formTable td div.el-form-item{
  font-size:14px;
  margin-top:8px;
  margin-left:15px;
}
.formTable th{
  font-size:14px;
  border-bottom:1px solid #dfe6ec;
  border-right:1px solid #dfe6ec;
  margin:0;
  width: 100px;
  background:#F5F7FA;
  line-height: 150%;
}
.inputtable{
  background:#ccc;
  line-height: 150%;
}
</style>
